import { useState, useEffect } from 'react';
import { Table, Input, Button, Form, Row, Col, Card, Space, App, Modal, Switch, Tag, Select } from 'antd';
import { getBatchJobList, deleteBatchJob, insertBatchJob, updateBatchJob, getBatchJobById } from '@/api/batchJob';
import AuthControl from '@/components/common/AuthControl';
import hasElementAuth from '@/utils/auth';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import BatchJobForm from './BatchJobForm';
import { getDictByCode } from '@/api/dict';

const BatchJobIndex = () => {
  const [form] = Form.useForm();
  const [addEditForm] = Form.useForm();
  const { modal, message } = App.useApp();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [drawerLoading, setDrawerLoading] = useState(false);
  const [system, setSystem] = useState('admin-batch'); // 添加系统状态，默认为admin-batch

  // 系统选项
  const [systemOptions,setSystemOptions] = useState([
    { label: 'admin-batch', value: 'admin-batch' }
  ]);
  const allSystemOptions = () => {
    getDictByCode('admin', { dictCode: 'batchSystem' }).then(res => {
      setSystemOptions(res.data.others)
    });
  };
  useEffect(() => {
    allSystemOptions();
  }, []);
  const getColumns = () => {
    const baseColumns = [
      {
        title: '任务名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '任务分组',
        dataIndex: 'jobGroup',
        key: 'jobGroup'
      },
      {
        title: '任务Bean',
        dataIndex: 'bean',
        key: 'bean'
      },
      {
        title: '执行表达式',
        dataIndex: 'cron',
        key: 'cron'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (_, record) => (
          <Tag color={record.status ? 'green' : 'red'}>
            {record.status ? '启用' : '停用'}
          </Tag>
        )
      }
    ];

    if (hasElementAuth(['edit', 'delete'])) {
      baseColumns.push({
        title: '操作',
        key: 'action',
        width: 250,
        render: (_, record) => (
          <Space>
            <AuthControl permission="edit">
              <Button icon={<EditOutlined />} onClick={() => openEditModal(record)}>编辑</Button>
            </AuthControl>
            <AuthControl permission="delete">
              <Button icon={<DeleteOutlined />} onClick={() => deleteById(record.id)} danger>删除</Button>
            </AuthControl>
          </Space>
        )
      });
    }

    return baseColumns;
  };

  const [searchForm, setSearchForm] = useState({
    size: 10,
    current: 1
  });

  const [total, setTotal] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false);

  /**
   * 查询定时任务列表
   */
  const searchBatchJobs = (formData, systemParam = system) => {
    setLoading(true);
    const params = formData || searchForm;
    getBatchJobList(systemParam, params)
      .then(res => {
        if (res.data && res.data.others) {
          setTableData(res.data.others);
          setTotal(res.data.total || 0);
        } else {
          setTableData([]);
          setTotal(0);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  /**
   * 删除定时任务
   */
  const deleteById = (id, systemParam = system) => {
    modal.confirm({
      title: '确定要删除吗？',
      content: '此操作将永久删除该数据，请谨慎操作。',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setLoading(true);
        deleteBatchJob(systemParam, id).then(() => {
          message.success('定时任务已成功删除');
          searchBatchJobs();
        })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  };

  /**
   * 打开新增模态框
   */
  const openAddModal = () => {
    setIsEditing(false);
    addEditForm.resetFields();
    setIsModalOpen(true);
  };

  /**
   * 打开编辑模态框
   */
  const openEditModal = (record, systemParam = system) => {
    setDrawerLoading(true);
    setIsEditing(true);
    setIsModalOpen(true);

    // 调用接口获取详细信息
    getBatchJobById(systemParam, record.id).then(res => {
      if (res.data) {
        addEditForm.setFieldsValue({
          id: res.data.id,
          name: res.data.name,
          jobGroup: res.data.jobGroup,
          bean: res.data.bean,
          cron: res.data.cron,
          errorStrategy: res.data.errorStrategy,
          status: res.data.status,
          concurrent: res.data.concurrent,
          remark: res.data.remark
        });
      }
    })
      .finally(() => {
        setDrawerLoading(false);
      });
  };

  /**
   * 关闭模态框
   */
  const closeModal = () => {
    setIsModalOpen(false);
    addEditForm.resetFields();
    setIsEditing(false);
  };

  /**
   * 保存定时任务数据
   */
  const saveBatchJobData = () => {
    addEditForm.validateFields().then(values => {
      setDrawerLoading(true);
      if (isEditing) {
        // 修改
        const updateData = {
          id: values.id,
          name: values.name,
          jobGroup: values.jobGroup,
          bean: values.bean,
          cron: values.cron,
          errorStrategy: values.errorStrategy,
          status: values.status,
          concurrent: values.concurrent,
          remark: values.remark
        };
        updateBatchJob(system, updateData).then(() => {
          message.success('定时任务信息已更新');
          closeModal();
          searchBatchJobs();
        }).finally(() => {
          setDrawerLoading(false);
        });
      } else {
        // 新增
        const addData = {
          name: values.name,
          jobGroup: values.jobGroup,
          bean: values.bean,
          cron: values.cron,
          errorStrategy: values.errorStrategy,
          status: values.status,
          concurrent: values.concurrent,
          remark: values.remark
        };
        insertBatchJob(system, addData).then(() => {
          message.success('新定时任务已添加');
          closeModal();
          searchBatchJobs();
        }).finally(() => {
          setDrawerLoading(false);
        });
      }
    });
  };

  useEffect(() => {
    searchBatchJobs();
  }, [system]); // 添加system作为依赖项

  const handleTableChange = (pagination) => {
    const formData = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    };

    // 如果pageSize发生变化，重置到第一页
    if (pagination.pageSize !== searchForm.size) {
      formData.current = 1;
    }

    setSearchForm(formData);
    searchBatchJobs(formData);
  };

  const handleSearch = (values) => {
    const formData = {
      ...searchForm,
      name: values.name || "",
      jobGroup: values.jobGroup || "",
      current: 1 // 重置为第一页
    };
    setSearchForm(formData);
    searchBatchJobs(formData);
  };

  return (
    <Card>
      <AuthControl permission="search">
        <Form form={form} onFinish={handleSearch}>
          <Row gutter={24}>
            <Col span={6}>
              <Form.Item label="系统">
                <Select 
                  value={system} 
                  onChange={setSystem}
                  options={systemOptions}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="name" label="任务名称">
                <Input placeholder="请输入任务名称" allowClear />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="jobGroup" label="任务分组">
                <Input placeholder="请输入任务分组" allowClear />
              </Form.Item>
            </Col>
            <Col span={6} style={{ textAlign: 'right' }}>
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading} icon={<SearchOutlined />} style={{ marginRight: 8 }}>
                  查询
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </AuthControl>
      <AuthControl permission="add">
        <Button loading={loading} type="primary" icon={<PlusOutlined />} style={{ marginBottom: 16 }} onClick={openAddModal}>
          添加
        </Button>
      </AuthControl>
      <Table
        columns={getColumns()}
        dataSource={tableData}
        rowKey="id"
        loading={loading}
        scroll={{ y: '45vh' }}
        pagination={{
          current: searchForm.current,
          pageSize: searchForm.size,
          total: total,
          showTotal: (total) => `共 ${total} 条数据`,
          showSizeChanger: true,
          pageSizeOptions: ['5', '10', '20', '50', '100']
        }}
        onChange={handleTableChange}
      />

      {/* 新增/编辑模态框 */}
      <Modal
        title={isEditing ? "编辑定时任务" : "新增定时任务"}
        open={isModalOpen}
        onCancel={closeModal}
        confirmLoading={drawerLoading}
        destroyOnHidden= {true}
        footer={[
          <Button key="cancel" onClick={closeModal}>取消</Button>,
          <Button key="save" type="primary" onClick={saveBatchJobData} loading={drawerLoading}>
            保存
          </Button>
        ]}
        width={600}
      >
        <BatchJobForm form={addEditForm} isEditing={isEditing} />
      </Modal>
    </Card>
  );
};

export default BatchJobIndex;